var redis = require('redis');
var http = require('http');
// var https = require('https');
var socketio = require('socket.io');

var server = http.createServer(function (req, res) {
  res.writeHead(200, {
    'Content-Type': 'text/plain'
  });
  res.end('服务器开启成功');
  console.log('服务器开启成功');
}).listen(4000);

var io = socketio(server);
io.on('connection', function (socket) {
  console.log('已上线');
  var credis = redis.createClient();
  credis.auth('123456');
  // 消息订阅者，即subscribe客户端，需要独占链接，
  var subscribe = redis.createClient();
  subscribe.auth('123456');
  //消息发布者，即publish客户端，无需独占链接
  var publish = redis.createClient();
  publish.auth('123456');
  //scoket监听订阅者在客户端订阅一个channel  
  socket.on('subscribe', function (channel, username) {
    credis.sadd('user:' + username, channel); //这里我们把用户每次订阅的channel放到了一个set中
    socket.emit('message', {
      channel: channel,
      username: username,
      data: '订阅成功'
    });
    subscribe.subscribe(channel);
  })
  //scoket监听订阅者在客户端取消订阅一个channel  
  socket.on('unsubscribe', function (channel, username) {
    socket.emit('message', {
      channel: channel,
      username: username,
      data: '取消订阅成功'
    });
    subscribe.unsubscribe(channel);
  })

  //socket监听发布者在某个channel上发布一条信息,消息发布者，即publish客户端
  // setInterval(function () {
  // http.get('', function (data) {
  //   var html = '';
  //   data.on('data', function (chunk) {
  //     html += chunk;
  //   })
  //   data.on('end', function () {
  //     console.log(html);
  //   })
  // })
  // }, 5000)
  socket.on('publish', (channel, data) => {
    publish.publish(channel, data);
  });

  //服务器接受页面断开重新刷新后重新加载已经订阅的channel(redis的单连接问题),消息订阅者，即subscribe客户端 
  socket.on('suballscribe', function (channelArr, username) {
    // console.log('channelArr');
    for (var i = 0; i < channelArr.length; i++) {
      subscribe.subscribe(channelArr[i]);
    }
  })
  //群发
  socket.on('groups', function (channel, message, pattern) {
    io.sockets.emit('message', {
      channel: channel,
      data: message,
      pattern: pattern
    })
  })
  //发布者在某个channel发送消息的时候,订阅频道的redis链接监听这个消息和该频道  
  subscribe.on('message', function (channel, message, pattern) {
    socket.emit('message', {
      channel: channel,
      data: message,
      pattern: pattern
    })
  })
  //某某下线了
  socket.on('downline', function (username) {
    // console.log(username);
    socket.emit('message', {
      code: -1,
      username: username,
      data: '下线了',
    })
    socket.on('disconnect', function () {
      console.log(username + '离开了');
    });
  });
  socket.on('disconnect', function () {
    console.log('离开了');
  });
});